
package com.lemon.cloud.oauth.support.handler;

import cn.hutool.core.util.StrUtil;
import com.lemon.cloud.comm.constants.CommonConstants;
import com.lemon.cloud.comm.constants.OAuth2Constant;
import com.lemon.cloud.comm.constants.enums.LogBusType;
import com.lemon.cloud.comm.model.ResultMsg;
import com.lemon.cloud.core.utils.MsgUtils;
import com.lemon.cloud.core.utils.SpringContextHolder;
import com.lemon.cloud.log.entity.Log;
import com.lemon.cloud.log.event.SysLogEvent;
import com.lemon.cloud.log.utils.SysLogUtils;
import com.lemon.cloud.security.enums.GrantTypeEnum;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.MediaType;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.http.server.ServletServerHttpResponse;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.oauth2.core.OAuth2AuthenticationException;
import org.springframework.security.oauth2.core.endpoint.OAuth2ParameterNames;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author huangds
 * @date 2022-06-02
 */
@Slf4j
public class AuthenticationFailureEventHandler implements AuthenticationFailureHandler {

	private final MappingJackson2HttpMessageConverter errorHttpResponseConverter = new MappingJackson2HttpMessageConverter();

	/**
	 * Called when an authentication attempt fails.
	 * @param request the request during which the authentication attempt occurred.
	 * @param response the response.
	 * @param exception the exception which was thrown to reject the authentication
	 * request.
	 */
	@Override
	@SneakyThrows
	public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response,
			AuthenticationException exception) {
		String username = request.getParameter(OAuth2ParameterNames.USERNAME);
		String title = "登录失败";
		if (request.getRequestURI().contains(OAuth2Constant.CHECK_TOKEN_URI)){
			title = "校验token失败";
		}
		log.info("用户：{} {}，异常：{}", username,title, exception.getLocalizedMessage());
		Log logVo = SysLogUtils.getSysLog();
		logVo.setTitle(title);
		logVo.setType(LogBusType.ERROR.name());
		logVo.setServiceId(LogBusType.ERROR.name());
		logVo.setException(exception.getLocalizedMessage());
		// 发送异步日志事件
		String startTimeStr = request.getHeader(CommonConstants.REQUEST_START_TIME);
		if (StrUtil.isNotBlank(startTimeStr)) {
			Long startTime = Long.parseLong(startTimeStr);
			Long endTime = System.currentTimeMillis();
			logVo.setTime(endTime - startTime);
		}
		logVo.setCreateBy(username);
		SpringContextHolder.publishEvent(new SysLogEvent(logVo));
		// 写出错误信息
		sendErrorResponse(request, response, exception);
	}

	private void sendErrorResponse(HttpServletRequest request, HttpServletResponse response,
			AuthenticationException exception) throws IOException {
		ServletServerHttpResponse httpResponse = new ServletServerHttpResponse(response);
		String errorMessage;

		if (exception instanceof OAuth2AuthenticationException) {
			OAuth2AuthenticationException authorizationException = (OAuth2AuthenticationException) exception;
			errorMessage = StrUtil.isBlank(authorizationException.getError().getDescription())
					? authorizationException.getError().getErrorCode()
					: authorizationException.getError().getDescription();
		}
		else {
			errorMessage = exception.getLocalizedMessage();
		}

		// 手机号登录
		String grantType = request.getParameter(OAuth2ParameterNames.GRANT_TYPE);
		if (GrantTypeEnum.MOBILE_CODE.getType().equals(grantType)) {
			errorMessage = MsgUtils.getSecurityMessage("AbstractUserDetailsAuthenticationProvider.smsBadCredentials");
		}

		this.errorHttpResponseConverter.write(ResultMsg.resultFail(errorMessage), MediaType.APPLICATION_JSON, httpResponse);
	}

}
